<!-- 职务管理 -->
<template>
  <div class="position-page art-full-height">
    <!-- 搜索栏 -->
    <PositionSearch
      v-show="showSearchBar"
      v-model="searchForm"
      @search="handleSearch"
      @reset="resetSearchParams"
    />

    <ElCard
      class="art-table-card"
      shadow="never"
      :style="{ 'margin-top': showSearchBar ? '12px' : '0' }"
    >
      <!-- 表格头部 -->
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap>
            <ElButton type="primary" @click="showDialog('add')" v-ripple>
              新增职务
            </ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      />
    </ElCard>

    <!-- 职务编辑弹窗 -->
    <PositionDialog
      v-model:visible="dialogVisible"
      :type="dialogType"
      :position-data="currentPositionData"
      @submit="handleDialogSubmit"
    />
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Edit, Delete } from '@element-plus/icons-vue'
  import { useTable } from '@/composables/useTable'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import PositionSearch from './modules/position-search.vue'
  import PositionDialog from './modules/position-dialog.vue'
  import {
    apiPositionPageDataUsingPost,
    apiPositionDeleteDataUsingPost,
    type ApiPositionVo
  } from '@/api'

  defineOptions({ name: 'Position' })

  type PositionListItem = ApiPositionVo

  // 搜索表单
  const searchForm = ref({
    positionName: undefined
  })

  const showSearchBar = ref(false)

  // 弹窗相关
  const dialogVisible = ref(false)
  const dialogType = ref<'add' | 'edit'>('add')
  const currentPositionData = ref<PositionListItem | undefined>(undefined)

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: apiPositionPageDataUsingPost,
      apiParams: {
        body: {}
      },
      paginationWrapper: 'body',
      columnsFactory: () => [
        { type: 'index', width: 60, label: '序号' },
        {
          prop: 'positionName',
          label: '职务名称',
          minWidth: 150
        },
        {
          prop: 'positionLevel',
          label: '职级',
          width: 120
        },
        {
          prop: 'positionSort',
          label: '排序',
          width: 100,
          sortable: true
        },
        {
          prop: 'positionRemark',
          label: '备注',
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'createTime',
          label: '创建时间',
          width: 180,
          sortable: true
        },
        {
          prop: 'operation',
          label: '操作',
          fixed: 'right',
          formatter: (row) =>
            h('div', { class: 'table-operations' }, [
              h(ArtButtonTable, {
                type: 'edit',
                onClick: () => showDialog('edit', row)
              }),
              h(ArtButtonTable, {
                type: 'delete',
                onClick: () => deletePosition(row)
              })
            ])
        }
      ]
    }
  })

  /**
   * 显示对话框
   */
  const showDialog = (type: 'add' | 'edit', row?: PositionListItem) => {
    dialogVisible.value = true
    dialogType.value = type
    currentPositionData.value = row
  }

  /**
   * 搜索处理
   */
  const handleSearch = (params: Record<string, any>) => {
    // 确保搜索参数被包装到body对象中
    if (!searchParams.body) {
      searchParams.body = {}
    }
    Object.assign(searchParams.body, params)
    getData()
  }

  /**
   * 对话框提交成功
   */
  const handleDialogSubmit = () => {
    refreshData()
  }

  /**
   * 删除职务
   */
  const deletePosition = (row: PositionListItem) => {
    ElMessageBox.confirm(`确定删除职务"${row.positionName}"吗？此操作不可恢复！`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          const res = await apiPositionDeleteDataUsingPost({
            body: { id: row.id }
          })
          if (res) {
            ElMessage.success('删除成功')
            refreshData()
          } else {
            ElMessage.error('删除失败')
          }
        } catch (error) {
          console.error('删除职务失败:', error)
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  }
</script>

<style lang="scss" scoped>
  .position-page {
    padding-bottom: 15px;

    :deep(.table-operations) {
      display: flex;
      gap: 8px;
    }
  }
</style>
